package com.only.webServer.request;

import com.only.webServer.content.ContentTypeHandle;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RequestUtils {

    /**
     * 校验请求头
     * @param requestHeader 请求头
     * @return 校验是否成功
     */
    public static Boolean isRequestHeader(String requestHeader) {
        if (requestHeader == null || "".equals(requestHeader)) {
            return false;
        }
        String httpRegex = "^(?:GET|POST|PUT|DELETE) (?:/.*) HTTP/[\\\\d.]+\\r?\\\\n(?:(?:.*): (?:.*)\\r?\\\\n)+\\r?\\\\n(.*\\\\n)*";
        return requestHeader.matches(httpRegex);
    }

    /**
     * 获取HttpRequest对象
     * @param request
     * @return
     */
    public static HttpRequest getHttpRequest(String request) {
        HttpRequest httpRequest = new HttpRequest();
        String regex = "\r\n\r\n";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(request);
        matcher.find();
        // 请求头
        String head = request.substring(0, matcher.end());
        handleRequestHead(httpRequest, head);
        // 请求体
        String body = request.substring(matcher.end());
        if (!"".equals(body)) {
            handleRequestBody(httpRequest, body);
        }
        return httpRequest;
    }


    private static void handleRequestHead(HttpRequest httpRequest, String head) {
        // 获取第一行数据
        String getFirstRegex = "(GET|POST|PUT|DELETE) (/.*) HTTP/[\\d.]+\r?\n";
        Pattern first = Pattern.compile(getFirstRegex);
        Matcher matcher = first.matcher(head);
        matcher.find();
        httpRequest.setMethod(HttpMethod.valueOf(matcher.group(1)));
        httpRequest.setPathMapping(matcher.group(2));

        // 解析路由参数
        String pathMapping = httpRequest.getPathMapping();
        String[] split = pathMapping.split("\\?");
        if (split.length > 1) {
            String params = split[1];
            Map<String, String> pathParams = getPathParams(params);
            httpRequest.setParameters(pathParams);
        }
        httpRequest.setPathMapping(split[0]);

        // 解析请求头其他行数据
        String keyValues = "(.*): (.*)\r?\n";
        Pattern pattern = Pattern.compile(keyValues);
        Matcher matcher1 = pattern.matcher(head);
        while (matcher1.find()) {
            httpRequest.setHeader(matcher1.group(1), matcher1.group(2));
        }
    }

    /**
     * 获取路径参数
     * @param path
     * @return
     */
    public static Map<String, String> getPathParams(String path) {
        String[] split = path.split("&");
        Map<String, String> map = new HashMap<>();
        String paramRegex = "^(.*)=(.*)$";
        Pattern paramPattern = Pattern.compile(paramRegex);
        for (String s : split) {
            Matcher paramMatcher = paramPattern.matcher(s);
            if (paramMatcher.matches()) {
                map.put(paramMatcher.group(1), paramMatcher.group(2));
            }
        }
        return map;
    }


    /**
     * 请求体
     * @param httpRequest
     * @param body  请求体报文
     */
    private static void handleRequestBody(HttpRequest httpRequest, String body) {
        String contentType = httpRequest.getHeader("Content-Type");
        String[] split = contentType.split(";");
        ContentTypeHandle typeHandle = ContentTypeHandle.handleMap.get(split[0]);
        if (typeHandle == null) {
            httpRequest.setPathMapping("/500");
            return;
        }
        typeHandle.handle(httpRequest, body);
    }
}
